//
//  LspNbLoginViewController.swift
//  LspSwiftFinayTest
//
//  Created by lsp's mac pro on 2018/4/20.
//  Copyright © 2018年 lsp's mac pro. All rights reserved.
//

import UIKit


class LspNbLoginViewController: UIViewController {
    let webView = UIWebView()
    
    override func loadView() {
        
        view=webView
        webView.backgroundColor=UIColor.white
        webView.scrollView.isScrollEnabled=false
        //设置导航栏
        self.title="登录"
        webView.delegate=self
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(closeThisView), isBack: true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 16, target: self, action: #selector(clcikTextAndPwd), isBack: false)
    }
   
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppkey)&redirect_uri=\(WBReditrctURL)"
        
        guard let url = URL(string: urlString)  else {
            return
        }
        //这边应为URL(string:string)是可选的 这里可以用！强行解包，但是最好的使用guard let 守护
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
        

        // Do any additional setup after loading the view.
    }

    
   @objc func closeThisView() {
       SVProgressHUD.dismiss()
       dismiss(animated: true, completion: nil);
    }
    
    @objc func clcikTextAndPwd(){
        let jsString = "document.getElementById('userId').value = '454996720@qq.com';"+"document.getElementById('passwd').value = 'lishupeng0812';"
        
        webView.stringByEvaluatingJavaScript(from: jsString);
        
    }
    

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

extension LspNbLoginViewController :UIWebViewDelegate{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        if request.url?.absoluteString.hasPrefix(WBReditrctURL)==false {
            return true
        }
        
        
        //1.请求地址里面包含回掉的话先加载页面
        
        if  request.url?.query?.hasPrefix("code=")==false  {
          closeThisView()
           return false
        }
       //http://www.baidu.com/?code=f373f59a8b5adb15d0c20a87abe61697
        
        
        //swift 4.0 方法
        let code = String( describing: request.url?.query?["code=".endIndex...] ?? "")
        
      
        
        //swift 3.0 方法
//      let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("授权码 - \(code)")
        LspNbNetWorkManage.shared.getUserToken(code: code) { (isSuccess) in
            if !isSuccess{
              SVProgressHUD.showInfo(withStatus: "网络请求失败")
                
            }else{
                SVProgressHUD.showInfo(withStatus: "登录成功")
                
               NotificationCenter.default.post(name: NSNotification.Name(rawValue: succeLoginUser), object: nil)
                
                self.closeThisView()
                
            }
        }
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
     SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
      SVProgressHUD.dismiss()
    }
}
